package com.cly.utils;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson2.filter.ValueFilter;
import com.cly.note.MaskedData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 脱敏信息序列化
 *
 * @author by 春风能解释
 * <p>
 * 2024/10/17
 */
@Slf4j
@Component
public class SensitiveInfoSerializer implements ValueFilter {
    /**
     * 脱敏处理
     *
     * @param object 目标对象
     * @param name   字段名
     * @param value  字段值
     * @return 处理后的值
     */
    @Override
    public Object apply(Object object, String name, Object value) {
        // 非字符串类型直接返回
        if (!(value instanceof String) || !StringUtils.hasText((String) value)) {
            return value;
        }
        // 获取字段
        Field field = ReflectUtil.getField(object.getClass(), name);
        if (Objects.isNull(field)) {
            return value;
        }
        MaskedData annotation;
        // 非字符串类型直接返回
        if (Objects.isNull(annotation = field.getAnnotation(MaskedData.class))) {
            return value;
        }
        DesensitizedUtil.DesensitizedType desensitizedType = annotation.value();
        log.info("已完成对字段{}的脱敏", name);
        return DesensitizedUtil.desensitized(value.toString(), desensitizedType);
    }
}
